<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.taskName"
          clearable
          size="small"
          placeholder="输入任务名称搜索"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="toQuery"
        />
        <date-range-picker v-model="query.createTime" class="date-item" />
        <rrOperation />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!--Form表单-->
    <el-dialog
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      append-to-body
      width="730px"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        size="small"
        label-width="100px"
      >
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" />
        </el-form-item>
        <el-form-item label="源素材" prop="uploadTaskData.id">
          <el-select
            v-model="form.uploadTaskData.id"
            filterable
            placeholder="请选择"
            style="width:100%"
          >
            <el-option
              v-for="item in sourceFileOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务描述">
          <el-input v-model="form.description" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button
          :loading="crud.status.cu === 2"
          type="primary"
          @click="crud.submitCU"
          >确认</el-button
        >
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      style="width: 100%;"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column :selectable="checkboxT" type="selection" width="55" />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="id"
        width="100px"
        label="任务ID"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="taskName"
        label="任务名称"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="uploadTaskData.name"
        label="源素材"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="description"
        label="描述"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        prop="createTime"
        width="150px"
        label="创建日期"
      />
      <el-table-column
        align="center"
        :show-overflow-tooltip="true"
        width="120px"
        prop="status"
        label="状态"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 'PENDING'">就绪</el-tag>
          <el-tag v-else-if="scope.row.status == 'RUNNING'" type="success"
            >运行中</el-tag
          >
          <el-tag v-else-if="scope.row.status == 'COMPLETED'" type="info"
            >完成</el-tag
          >
          <el-tag v-else-if="scope.row.status == 'ERROR'" type="danger"
            >错误</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="outputAddress"
        width="120px"
        label="输出下载"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status == 'COMPLETED'"
            :loading="fileLoading === scope.row.id"
            icon="el-icon-download"
            size="mini"
            @click="downloadOutputFile(scope.row.id, scope.row.outputAddress)"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-if="checkPer(['admin', 'task:run', 'task:edit', 'task:del'])"
        label="操作"
        width="230px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="['admin', 'task:run']"
            style="margin-left: 3px"
            type="primary"
            size="mini"
            @click="regional(scope.row)"
          >
            执行
          </el-button>
          <el-button
            v-permission="['admin', 'task:edit']"
            size="mini"
            style="margin-right: 3px;"
            type="success"
            icon="el-icon-edit"
            @click="crud.toEdit(scope.row)"
          />
          <el-popover
            :ref="scope.row.id"
            v-permission="['admin', 'task:del']"
            placement="top"
            width="200"
          >
            <p>确定停止并删除该任务吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button
                size="mini"
                type="text"
                @click="$refs[scope.row.id].doClose()"
                >取消</el-button
              >
              <el-button
                :loading="delLoading"
                type="primary"
                size="mini"
                @click="delMethod(scope.row.id)"
                >确定</el-button
              >
            </div>
            <el-button
              slot="reference"
              type="danger"
              icon="el-icon-delete"
              size="mini"
            />
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
    <!--区域坐标弹框-->
    <regional ref="regionalRef" />
  </div>
</template>

<script>
import crudJob from '@/api/system/task'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker'
import { parseTime } from '@/utils/index'
import regional from './regional.vue'
import { getToken } from '@/utils/auth' // getToken from cookie

const defaultForm = {
  id: null,
  taskName: null,
  uploadTaskData: { id: null },
  description: null
}
export default {
  name: 'Task',
  components: {
    pagination,
    crudOperation,
    rrOperation,
    DateRangePicker,
    regional
  },
  cruds() {
    return CRUD({
      title: '任务',
      url: '/api/tasks',
      crudMethod: { ...crudJob }
    })
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  created() {
    this.crud.optShow = {
      add: true,
      edit: false,
      del: true,
      download: false
    }
    this.$nextTick(() => {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setInterval(this.crud.refresh, 5000)
      crudJob
        .getSourceFiles()
        .then(res => {
          if (res) {
            this.sourceFileOptions = res.content
          }
        })
        .catch(() => {})
    })
  },
  beforeDestroy() {
    if (this.timer) {
      clearTimeout(this.timer)
    }
  },
  data() {
    return {
      delLoading: false,
      fileLoading: null,
      permission: {
        add: ['admin', 'task:add'],
        edit: ['admin', 'task:edit'],
        del: ['admin', 'task:del']
      },
      timer: null,
      rules: {
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        uploadTaskData: [
          { required: true, message: '请选择源文件', trigger: 'blur' }
        ]
      },
      sourceFileOptions: []
    }
  },
  methods: {
    regional(row) {
      const _this = this.$refs.regionalRef
      _this.dialog = true
      _this.taskId = row.id
      _this.urlVideo = `${window.VUE_APP_API_SERVER_ADDRESS}/api/download/${
        row.uploadTaskData.id
      }?type=sourceVideo&token=${getToken()}`
      _this.initCanvas()
    },
    delMethod(id) {
      this.delLoading = true
      crudJob
        .del([id])
        .then(() => {
          this.delLoading = false
          this.$refs[id].doClose()
          this.crud.dleChangePage(1)
          this.crud.delSuccessNotify()
          this.crud.toQuery()
        })
        .catch(() => {
          this.delLoading = false
          this.$refs[id].doClose()
        })
    },
    checkboxT(row) {
      return row.id > 0
    },
    downloadOutputFile(id, outputAddress) {
      this.fileLoading = id
      const { token } = this.$store.getters
      crudJob
        .downloadFile(id, token)
        .then(res => {
          const url = window.URL.createObjectURL(new Blob([res]))
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          const arr_name = outputAddress.split('.')
          const suffix = arr_name[arr_name.length - 1]
          const fileName = parseTime(new Date()) + '-' + id + '.' + suffix
          link.setAttribute('download', fileName)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          this.fileLoading = null
        })
        .catch(() => {
          this.fileLoading = null
        })
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (!crud.form.uploadTaskData.id) {
        this.$message({
          message: '源素材不能为空',
          type: 'warning'
        })
        return false
      }
      return true
    }
  }
}
</script>
